package com.example.web.websystem.interceptor;

import com.example.web.websystem.response.BusinessError;
import com.example.web.websystem.response.GlobalCodeEnum;
import com.example.web.websystem.token.manage.TokenHandle;
import com.example.web.websystem.token.manage.TokenObject;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = TokenHandle.getToken(request);
        //1，是否存在token
        if (token == null) throw new BusinessError(GlobalCodeEnum.NO_LOGIN);
        try {
            //2，校验token是否有效，返回为null表示有效
            GlobalCodeEnum codeEnum = TokenHandle.verifyToken(token);
            if (codeEnum != null) throw new BusinessError(codeEnum);
            //3,解析token，查看字段值是否有效
            TokenObject tokenObject = TokenHandle.parse(token);
            if (tokenObject == null || tokenObject.getUserId() == null) {
                throw new BusinessError(GlobalCodeEnum.TOKEN_IS_EMPTY);
            }
        } catch (BusinessError e) {
            throw e;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
